package middleware

import (
    . "api/util"
    "net/http"
    "github.com/gin-gonic/gin"
)

func Cors() gin.HandlerFunc {
    return func(c *gin.Context) {
        method := c.Request.Method
		origin := c.Request.Header.Get("Origin")

        if origin != "" {
            c.Header("Access-Control-Allow-Origin", "*")
			c.Header("Access-Control-Allow-Headers", "*")
			c.Header("Access-Control-Allow-Methods", "*")
		}

        if method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
		}

        c.Next()
    }
}

func AuthToken() gin.HandlerFunc {
    return func(c *gin.Context) {
        if c.Request.RequestURI != "promotion_officer_info" || c.Request.RequestURI != "withdraw" || c.Request.RequestURI != "apprentices" {
            return
        }

        token := c.Request.Header.Get("Token")

        if token == "" {
            c.JSON(403, gin.H{"error": "403 Forbidden"})
            c.Abort()
            return
        }

        _, err := ParseCliamsToken(token)
        if err != nil {
            c.JSON(403, gin.H{"error": err.Error()})
            c.Abort()
            return
        }

        c.Next()
    }
}

func AuthAdminToken() gin.HandlerFunc {
    return func(c *gin.Context) {
        if c.Request.RequestURI == "/v1/admin/login" {
            return
        }

        token := c.Request.Header.Get("Token")

        if token == "" {
            c.JSON(403, gin.H{"error": "403 Forbidden"})
            c.Abort()
            return
        }

        _, err := ParseCliamsAdminToken(token)
        if err != nil {
            c.JSON(403, gin.H{"error": err.Error()})
            c.Abort()
            return
        }

        c.Next()
    }
}